"""
@Author：十
@Time：2024/7/29 17:16
@FileName：main.py
@Description：主窗口逻辑
"""
import os
import re
import sqlite3
import sys

import matplotlib
import matplotlib.dates as mdates
import pandas as pd
import pythoncom
from PyQt5.QtCore import Qt, pyqtSignal, QObject, pyqtSlot
from PyQt5.QtGui import QCursor
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtWidgets import QApplication, QWidget, QTreeWidgetItem, QTableWidgetItem, QPushButton, QHBoxLayout
from matplotlib.backend_bases import MouseEvent, MouseButton
from loguru import logger
from win32com import client as win32

import EdgeIOT
from UI.item import DCR_Widget
from UI.item import LR_Widget
from UI.item import EarthContinuity_Widget
from UI.main import Ui_Form
from UI.manager import M_DCR_Widget
from UI.manager import M_LR_Widget
from UI.manager import M_EC_Widget
from detect import DeleteWindow
from export import ExportWindow
from fileRecognition import fileRecognition
from instrument import InstrumentWindow
from setup import SetupWindow
from upload import UploadWindow
import loggingConfig


# label点击父类
class Clickable(QObject):
    clicked = pyqtSignal()

    def __init__(self, label):
        super(Clickable, self).__init__()
        self.label = label
        self.label.installEventFilter(self)

    def eventFilter(self, obj, event):
        if obj == self.label:
            if event.type() == event.MouseButtonPress and event.button() == Qt.LeftButton:
                self.clicked.emit()
                return True
            elif event.type() == event.Enter:
                # 设置鼠标进入时的光标形状
                self.label.setCursor(QCursor(Qt.PointingHandCursor))
            elif event.type() == event.Leave:
                # 设置鼠标离开时的光标形状恢复
                self.label.setCursor(QCursor(Qt.ArrowCursor))
        return super(Clickable, self).eventFilter(obj, event)


class MainWindow(QWidget, Ui_Form):
    # 设备信息传递信号
    Signal_Get_Instrument = pyqtSignal(object)
    # 数据提交信号
    Signal_Submit_Data = pyqtSignal(object, object)

    def __init__(self):

        super(MainWindow, self).__init__()

        self.data_widgets = []

        self.setupUi(self)

        # 仪器信息窗口
        # self.InstrumentWindow = InstrumentWindow(self)
        self.Signal_Get_Instrument.connect(self.GetInstrument)
        # 导出报告窗口
        self.ExportWindow = ExportWindow(self)
        # 监测信息设置窗口
        self.SetupWindow = SetupWindow(self)
        # 数据上传窗口
        self.UploadWindow = UploadWindow(self)
        # 监测站点窗口
        self.DetectWindow = DeleteWindow(self)
        # 解析文件工具类
        self.FileRecognition = fileRecognition(self)
        # 日志配置初始化
        loggingConfig.setup_logging()

        # 界面初始化
        self.InterfaceInit()
        # 连接mqtt服务器
        self.ConnectMQTT()

        # 仪器信息修改按钮弹出
        self.pushButton_Modify.clicked.connect(self.ShowModify)
        # 设备树点选
        self.treeWidget.itemClicked.connect(self.onItemClicked)
        # tabWidget"数据管理"点击刷新
        self.tabWidget.tabBarClicked.connect(self.RefreshData)
        # 刷新按钮
        self.pushButton_Refresh.clicked.connect(self.refresh_layout)

        # 日期过滤器
        self.is_updating = False
        self.checkboxes = [self.checkBox_1, self.checkBox_2, self.checkBox_3]
        self.checkBox_All.stateChanged.connect(self.handle_select_all)
        for checkbox in self.checkboxes:
            checkbox.stateChanged.connect(self.handle_option_changed)

        # # 点击切换展示页面
        # self.list_label = Clickable(self.label_List)
        # self.list_label.clicked.connect(self.ShowList)
        # self.info_label = Clickable(self.label_Chart)
        # self.info_label.clicked.connect(self.ShowChart)
        # 点击刷新
        # self.refresh_label = Clickable(self.label_Refresh)
        # self.refresh_label.clicked.connect(self.RefreshList)

        # "数据管理"按钮
        self.pushButton_Manage.clicked.connect(self.DataSave)

        # 检测站点窗口确认后提交信息
        self.Signal_Submit_Data.connect(self.SubmitData)

        # 存储鼠标按下信息和轴限制的变量
        self.press = None
        self.x_min = None
        self.x_max = None
        self.y_min = None
        self.y_max = None
        self.initial_xlim = None
        self.initial_ylim = None

    # 时间点过滤
    def handle_select_all(self, state):
        try:
            if self.is_updating:
                return
            self.is_updating = True
            # 当全选复选框状态改变时，更新所有选项复选框的状态
            for checkbox in self.checkboxes:
                checkbox.setChecked(state == Qt.Checked)
            self.is_updating = False
        except Exception as e:
            print('全选错误：', e)

    def handle_option_changed(self, state):
        try:
            if self.is_updating:
                return
            self.is_updating = True
            if state == Qt.Unchecked:
                self.checkBox_All.setChecked(False)
            else:
                all_checked = all(checkbox.isChecked() for checkbox in self.checkboxes)
                if all_checked:
                    self.checkBox_All.setChecked(True)
            self.is_updating = False
        except Exception as e:
            print('单选错误：', e)

    # 界面初始化
    def InterfaceInit(self):
        try:
            self.setAutoFillBackground(True)
            # “数据管理”按钮在没有选中数据时不可用
            self.pushButton_Manage.setEnabled(False)
            self.ShowDeviceTree()
        except Exception as e:
            print('Init Interface ERROR:', e)

        self.createDB()

    # 软件打开时发送连接到MQTT服务器的connect command报文，获取connect ack之后显示“连接成功”信息
    def ConnectMQTT(self):
        if EdgeIOT.ConnectMQTT(callback=self.UploadWindow.SiteWindow.MessageReceived):
            self.label_State.setText('已连接状态感知平台')
            self.label_State.setStyleSheet('color:green')

    # 切换到列表界面
    def ShowList(self, instrument):
        if instrument == '直流电阻测试仪':
            self.DCR_TableData()
        elif instrument == '回路电阻测试仪':
            self.LR_TableData()
        elif instrument == '接地导通仪':
            self.EC_TableData()

    # 切换到分析图界面
    def ShowChart(self, instrument):
        if instrument == '直流电阻测试仪':
            self.DCR_ChartData()
        elif instrument == '回路电阻测试仪':
            self.LR_ChartData()
        elif instrument == '接地导通仪':
            self.EC_ChartData()

    # 刷新列表
    def RefreshList(self, instrument):
        if instrument == '直流电阻测试仪':
            self.DCR_TableData()
        elif instrument == '回路电阻测试仪':
            self.LR_TableData()
        elif instrument == '接地导通仪':
            self.EC_TableData()

    # 获取子窗口仪器信息
    def GetInstrument(self, instrument):
        try:
            self.label_Factory.setText(instrument['Factory'])
            self.label_Number.setText(instrument['ID'])
            self.label_Instrument.setText(instrument['Type'])
            self.clearLayout(self.gridLayout_2)
        except Exception as e:
            print('Main Window Show Instrument ERROR:', e)
            logger.critical('子窗口传递参数或清空数据窗口错误：', e)
        finally:
            # 解析文件
            self.Recognize(instrument['Type'])

    # 打开应用时创建数据库
    def createDB(self):
        db = QSqlDatabase.addDatabase('QSQLITE')

        try:
            # 建库
            db.setDatabaseName('./DB/digitization.db')
            db.open()
        except Exception as e:
            print('Create DB ERROR:', e)

        query = QSqlQuery()

        # 建表
        # 仪器信息存储
        try:
            query.exec('create table manufacturers_info(id integer PRIMARY KEY autoincrement, manufacturers text, code integer)')
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_manufacturers_info ON manufacturers_info (manufacturers, code)')
        except Exception as e:
            print('创建仪器厂家和仪器编号数据库失败:', e)
            logger.critical('创建仪器厂家和仪器编号数据库失败:', e)

        # 检测站点
        try:
            query.exec('create table detect_info(id integer PRIMARY KEY autoincrement, station text, vol text, device text, pos text)')
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_detect_info ON detect_info (station, pos)')
        except Exception as e:
            print('创建监测站点据库失败:', e)
            logger.critical('创建检测站点数据库失败:', e)

        # 介损测试
        try:
            query.exec(
                'create table d_loss_data(id integer PRIMARY KEY autoincrement, test_mode text, test_time text, test_voltage float(10), test_frequency text,c1_tgx float(10), '
                'c1_cx float(10), c1_pf float(10), c1_ix float(10), c1_pr float(10), c2_tgx float(10), c2_cx float(10), c2_pf float(10), c2_ix float(10), c2_pr float(10), '
                'c12_tgx float(10),c12_cx float(10), c12_pf float(10), c12_ix float(10), c12_pr float(10), station text, position text, has_delete BOOL, has_report BOOL)')
        except Exception as e:
            print("创建介损测试仪数据库失败：", e)
            logger.critical('创建介损测试仪数据库失败:', e)

        # 直流电阻测试仪
        try:
            query.exec('create table dcr_data(id integer PRIMARY KEY autoincrement, test_time text, test_mode text, test_number integer, test_electricity float(10), '
                       'resistor_AO float(10), resistor_BO float(10), resistor_CO float(10), maximum_unbalance_rate float(10), station text, position text, has_delete BOOL, '
                       'has_report BOOL)')
            # 创建唯一索引
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_dcr_data ON dcr_data (test_time, test_mode, test_electricity, resistor_AO, resistor_BO, resistor_CO)')
        except Exception as e:
            print("创建直流电阻测试仪数据库失败：", e)
            logger.critical('创建直流电阻测试仪数据库失败:', e)

        # 直流系统测试仪
        try:
            query.exec(
                'create table dc_data(id integer PRIMARY KEY autoincrement, test_mode text, test_time text, test_voltage float(10), test_frequency float(10),c1_tgx float(10), '
                'c1_cx float(10), c1_pf float(10), c1_ix float(10), c1_pr float(10), c2_tgx float(10), c2_cx float(10), c2_pf float(10), c2_ix float(10), c2_pr float(10), '
                'c12_tgx float(10),c12_cx float(10), c12_pf float(10), c12_ix float(10), c12_pr float(10), station text, position text,has_delete BOOL, has_report BOOL)')
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_dc_data ON dc_data (test_time, test_mode, test_voltage)')
        except Exception as e:
            print("创建直流系统测试仪数据库失败：", e)
            logger.critical('创建直流系统测试仪数据库失败:', e)

        # SF6密度继电器校验仪
        try:
            query.exec(
                'create table sf6_dr_data(id integer PRIMARY KEY autoincrement, test_time text, flag text, state1 text, state2 text, state3 text,state4 text, phase float(10), '
                'station text, position text, has_delete BOOL, has_report BOOL)')
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_sf6_data ON sf6_dr_data (test_time, flag, phase)')

        except Exception as e:
            print("创建直流系统测试仪数据库失败：", e)
            logger.critical('创建直流系统测试仪数据库失败:', e)

        # 回路电阻测试仪
        try:
            query.exec(
                'create table loop_resistance_data(id integer PRIMARY KEY autoincrement, test_time text, resistance float(10), current float(10), voltage float(10),'
                'station text, position text, has_delete BOOL, has_report BOOL)')
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_lr_data ON loop_resistance_data (test_time, resistance, current, voltage)')
        except Exception as e:
            print("创建回路电阻测试仪数据库失败：", e)
            logger.critical('创建回路电阻测试仪数据库失败:', e)

        # 接地导通测试仪
        try:
            query.exec(
                'create table earth_continuity(id integer PRIMARY KEY autoincrement, test_time text, resistance float(10), current float(10),'
                'station text, position text, has_delete BOOL, has_report BOOL)')
            query.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_ec_data ON earth_continuity (test_time, resistance, current)')
        except Exception as e:
            print("创建回路电阻测试仪数据库失败：", e)
            logger.critical('创建回路电阻测试仪数据库失败:', e)

        db.close()

    # 识别设备
    def Recognize(self, instrument):
        file = "C:\\Users\\Administrator\\Desktop\\测试数据\\data"
        try:
            if file:
                for root, dirs, files in os.walk(file):
                    for file in files:
                        file_path = os.path.join(root, file)
                        file_extension = file.lower()
                        # print(file_path)
                        if instrument == '介损测试仪' and file_extension.endswith('.txt'):
                            # self.DielectricLossRecognition(file_path)
                            pass
                        elif instrument == '直流电阻测试仪' and file_extension.endswith('.txt'):
                            self.DirectCurrentResistance_UI_txt(file_path)
                        # elif instrument == '直流电阻测试仪' and file_extension.endswith('.csv'):
                        #     try:
                        #         self.DirectCurrentResistance_csv(file_path)
                        #     except Exception as e:
                        #         print(e)
                        elif instrument == '直流系统测试仪' and file_extension.endswith('.txt'):
                            self.DC_System(file_path)
                        elif instrument == '回路电阻测试仪' and file_extension.endswith('.doc'):
                            self.LoopResistanceTester_UI(file_path)
                        elif instrument == '接地导通仪' and file_extension.endswith('.txt'):
                            self.EarthContinuity_UI(file_path)
                        elif instrument == 'SF6密度继电器校验仪' and file_extension.endswith('.txt'):
                            try:
                                self.SF6DensityRelayCalibrator(file_path)
                            except Exception as e:
                                print(e)
        except Exception as e:
            print('识别设备类型失败：', e)
            logger.critical(f'识别设备类型失败:{e}')

    # 直流电阻测试仪txt文件添加到页面
    def DirectCurrentResistance_UI_txt(self, file_path):
        try:
            filtered_data_list = []
            data_list = self.FileRecognition.DirectCurrentResistance_txt(file_path)
            if data_list is not None:

                existing_data = self.FileRecognition.DCR_existing_data()

                for data in data_list:
                    if data not in existing_data:
                        filtered_data_list.append(data)

                row_count = 0
                column_count = 0
                for data in filtered_data_list:
                    data_widget = DCR_Widget(data, remove_callback=self.remove_widget)
                    data_widget.setMaximumSize(300, 170)
                    self.gridLayout_2.addWidget(data_widget, row_count, column_count)
                    self.data_widgets.append(data_widget)
                    column_count += 1
                    if column_count == 4:
                        column_count = 0
                        row_count += 1

            for widget in self.data_widgets:
                widget.selection_changed.connect(self.SignalChangeManageEnable)
        except Exception as e:
            print('直流电阻数据载入UI失败：', e)
            logger.critical(f'直流电阻数据载入UI失败：{e}')

    # 回路电阻测试仪
    def LoopResistanceTester_UI(self, file_path):
        try:
            filtered_data_list = []
            data_list = self.FileRecognition.LoopResistanceTester_DOC(file_path)
            if data_list is not None:

                existing_data = self.FileRecognition.LR_existing_data()

                for data in data_list:
                    if data not in existing_data:
                        filtered_data_list.append(data)

                row_count = 0
                column_count = 0
                for data in filtered_data_list:
                    data_widget = LR_Widget(data, remove_callback=self.remove_widget)
                    data_widget.setMaximumSize(300, 170)
                    self.gridLayout_2.addWidget(data_widget, row_count, column_count)
                    self.data_widgets.append(data_widget)
                    column_count += 1
                    if column_count == 4:
                        column_count = 0
                        row_count += 1

            for widget in self.data_widgets:
                widget.selection_changed.connect(self.SignalChangeManageEnable)
        except Exception as e:
            print('回路电阻数据载入UI失败：', e)
            logger.critical(f'回路电阻数据载入UI失败:{e}')

    # 接地导通仪txt文件添加到页面
    def EarthContinuity_UI(self, file_path):
        try:
            filtered_data_list = []
            data_list = self.FileRecognition.EarthContinuity_TXT(file_path)
            if data_list is not None:

                existing_data = self.FileRecognition.EC_existing_data()

                for data in data_list:
                    if data not in existing_data:
                        filtered_data_list.append(data)

                row_count = 0
                column_count = 0
                for data in filtered_data_list:
                    data_widget = EarthContinuity_Widget(data, remove_callback=self.remove_widget)
                    data_widget.setMaximumSize(300, 170)

                    self.gridLayout_2.addWidget(data_widget, row_count, column_count)
                    self.data_widgets.append(data_widget)
                    column_count += 1
                    if column_count == 4:
                        column_count = 0
                        row_count += 1

            for widget in self.data_widgets:
                widget.selection_changed.connect(self.SignalChangeManageEnable)
        except Exception as e:
            print('接地导通UI失败：', e)
            logger.critical(f'接地导通UI失败：{e}')

    # “数据管理”按钮的使能变换
    @pyqtSlot(bool)
    def SignalChangeManageEnable(self):
        try:
            any_selected = any(widget.selected for widget in self.data_widgets)
            if any_selected:
                self.pushButton_Manage.setEnabled(True)
            else:
                self.pushButton_Manage.setEnabled(False)
        except Exception as e:
            print('按钮转换使能失败：', e)

    def remove_widget(self, widget):
        self.gridLayout_2.removeWidget(widget)
        self.data_widgets.remove(widget)
        widget.deleteLater()
        self.refresh_layout()

    def refresh_layout(self):
        for i in reversed(range(self.gridLayout_2.count())):
            widget = self.gridLayout_2.itemAt(i).widget()
            if widget is not None:
                self.gridLayout_2.removeWidget(widget)
        row_count = 0
        column_count = 0
        for widget in self.data_widgets:
            self.gridLayout_2.addWidget(widget, row_count, column_count)
            column_count += 1
            if column_count == 4:
                column_count = 0
                row_count += 1

    # 这个函数是在监测数据确认之前
    def DataSave(self):
        try:
            self.ShowDetect()
        except Exception as e:
            print('打开检测站点窗口失败：', e)
            logger.critical(f'打开检测站点窗口失败：{e}')

    # 这个函数是在监测数据确认之后
    # 数据实际保存要在知道站点信息之后
    def SubmitData(self, station, pos):
        # 获取检测位置
        try:
            selected_data = [widget.data for widget in self.data_widgets if widget.selected]
            print("Selected Data:", selected_data)

            # 获取当前设备型号
            instrument = self.label_Instrument.text()
            # print(instrument)
            # print(station, pos)
            # 保存到数据库
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()
            if instrument == '直流电阻测试仪':
                for data in selected_data:
                    cursor.execute("""
                                INSERT OR IGNORE INTO dcr_data (test_time, test_electricity, test_mode, resistor_ao, resistor_bo, resistor_co, maximum_unbalance_rate,station, position, has_delete, has_report)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                            """, (data['test_time'], data['test_electricity'], data['test_mode'], data['resistor_ao'],
                                  data['resistor_bo'], data['resistor_co'], data['max_unbalance_rate'], station, pos, 0, 0))
            elif instrument == '回路电阻测试仪':
                for data in selected_data:
                    cursor.execute("""
                                INSERT OR IGNORE INTO loop_resistance_data (test_time, resistance, current, voltage,station, position, has_delete, has_report)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                            """, (data['test_time'], data['resistor'], data['current'], data['voltage'], station, pos, 0, 0))
            elif instrument == '接地导通仪':
                for data in selected_data:
                    cursor.execute("""
                                INSERT OR IGNORE INTO earth_continuity (test_time, resistance, current, station, position, has_delete, has_report)
                                VALUES (?, ?, ?, ?, ?, ?, ?)
                            """, (data['test_time'], data['resistor'], data['current'], station, pos, 0, 0))
            connection.commit()
            connection.close()

        except Exception as e:
            print('数据上传到数据库失败：', e)
            logger.critical(f'数据上传到数据库失败：{e}')

        # TODO： 再刷新数据管理界面的数据（打开程序的时候就要先查一遍）
        # try:
        #     if self.remove_callback:
        #         self.remove_callback(self)
        # except Exception as e:
        #     print('刷新数据失败：', e)

    # 数据库中已存在的数据从界面中移除
    def fetch_existing_data(self, instrument):
        connection = sqlite3.connect('./DB/digitization.db')
        cursor = connection.cursor()
        if instrument == '直流电阻测试仪':
            cursor.execute("SELECT test_time, test_mode, test_electricity, resistor_ao, resistor_bo, resistor_co, maximum_unbalance_rate FROM dcr_data")
        existing_data = cursor.fetchall()
        connection.close()
        return existing_data

    # 数据管理界面的treeWidget
    def ShowDeviceTree(self):

        self.treeWidget.clear()

        self.treeWidget.setColumnCount(2)

        connection = sqlite3.connect('./DB/digitization.db')
        cursor = connection.cursor()

        cursor.execute("SELECT station, pos FROM detect_info")
        records = cursor.fetchall()

        station_dict = {}
        for station, pos in records:
            if station not in station_dict:
                station_dict[station] = []
            station_dict[station].append(pos)

        for station, pos_list in station_dict.items():
            station_item = QTreeWidgetItem(self.treeWidget)
            station_item.setText(0, station)
            for pos in pos_list:
                pos_item = QTreeWidgetItem(station_item)
                pos_item.setText(1, pos)

        connection.close()

    # tree
    def onItemClicked(self, item):
        try:
            if item.parent() is not None:
                parent = item.parent()
                # result = parent.text(0) + " -> " + item.text(1)
                # print(result)
                self.ShowInstrumrnt(parent.text(0), item.text(1))
            else:
                if item.isExpanded():
                    item.setExpanded(False)
                else:
                    item.setExpanded(True)
                return item.text(0)
        except Exception as e:
            print(e)

    # 点击“数据管理”界面都数据库，刷新数据
    def RefreshData(self):
        try:
            self.ShowDeviceTree()
        except Exception as e:
            print('Refresh Data Error:', e)
            logger.critical(f'Refresh Data Error:{e}')

    # 选中“数据管理”中的节点后显示设备
    def ShowInstrumrnt(self, station, position):
        # 在数据库中查找该节点下的设备有哪些
        connection = sqlite3.connect('./DB/digitization.db')
        cursor = connection.cursor()
        try:
            # 清空显示界面
            for i in reversed(range(self.verticalLayout_3.count())):
                widget = self.verticalLayout_3.itemAt(i).widget()
                if widget is not None:
                    widget.deleteLater()

            # 直流电阻测试仪数据
            cursor.execute("SELECT * FROM dcr_data WHERE station = ? AND position = ? AND has_report = 0 AND has_delete = 0", (station, position))
            dcr_data = cursor.fetchall()

            # 回路电阻测试仪
            cursor.execute("SELECT * FROM loop_resistance_data WHERE station = ? AND position = ? AND has_report = 0 AND has_delete = 0", (station, position))
            lr_data = cursor.fetchall()
            # print('回路电阻测试仪数据库数据：', lr_data)

            # 接地导通仪
            cursor.execute("SELECT * FROM earth_continuity WHERE station = ? AND position = ? AND has_report = 0 AND has_delete = 0", (station, position))
            ec_data = cursor.fetchall()

            # 数据展示
            # 只要有的都展示
            if dcr_data:
                self.m_dcr_widget = M_DCR_Widget(self.scrollAreaWidgetContents_manager)
                self.verticalLayout_3.addWidget(self.m_dcr_widget)
                # 添加table
                self.DCR_TableData()
                # 添加label点击信号和槽
                self.m_dcr_widget.label_List.mousePressEvent = lambda event: self.ShowList('直流电阻测试仪')
                self.m_dcr_widget.label_Chart.mousePressEvent = lambda event: self.ShowChart('直流电阻测试仪')
                self.m_dcr_widget.label_Report.mousePressEvent = lambda event: self.ShowExport(self.m_dcr_widget)
                self.m_dcr_widget.label_Refresh.mousePressEvent = lambda event: self.RefreshList('直流电阻测试仪')
            if lr_data:
                self.m_lr_widget = M_LR_Widget(self.scrollAreaWidgetContents_manager)
                self.verticalLayout_3.addWidget(self.m_lr_widget)
                # 添加table
                self.LR_TableData()
                # 添加label点击信号和槽
                self.m_lr_widget.label_List.mousePressEvent = lambda event: self.ShowList("回路电阻测试仪")
                self.m_lr_widget.label_Chart.mousePressEvent = lambda event: self.ShowChart("回路电阻测试仪")
                self.m_lr_widget.label_Report.mousePressEvent = lambda event: self.ShowExport(self.m_lr_widget)
                self.m_lr_widget.label_Refresh.mousePressEvent = lambda event: self.RefreshList("回路电阻测试仪")
            if ec_data:
                self.m_ec_widget = M_EC_Widget(self.scrollAreaWidgetContents_manager)
                self.verticalLayout_3.addWidget(self.m_ec_widget)
                # 添加table
                self.EC_TableData()
                # 添加label点击信号和槽
                self.m_ec_widget.label_List.mousePressEvent = lambda event: self.ShowList("接地导通仪")
                self.m_ec_widget.label_Chart.mousePressEvent = lambda event: self.ShowChart("接地导通仪")
                self.m_ec_widget.label_Report.mousePressEvent = lambda event: self.ShowExport(self.m_ec_widget)
                self.m_ec_widget.label_Refresh.mousePressEvent = lambda event: self.RefreshList("接地导通仪")

            # 介损
            cursor.execute("SELECT * FROM d_loss_data WHERE station = ? AND position = ?  AND has_report = 0 AND has_delete = 0", (station, position))
            d_loss_data = cursor.fetchall()

            # print("\nMatching records in detect_info:")
            # if detect_info_data:
            #     for row in detect_info_data:

            #         print(row)
            # else:
            #     print("No matching records found in detect_info.")

            # print("\nMatching records in d_loss_data:")
            # if d_loss_data:
            #     for row in d_loss_data:
            #         print(row)
            # else:
            #     print("No matching records found in d_loss_data.")

        except sqlite3.Error as e:
            print(f"An error occurred: {e}")
            logger.critical('依据站点名查找设备数据失败:', e)

        finally:
            connection.close()

    def DCR_TableData(self):
        # 获取当前tree widget的节点
        station, position = self.Get_Tree_Node()

        # 隐藏绘图画布并显示表格部件
        self.m_dcr_widget.canvas.hide()
        self.m_dcr_widget.tableWidget.show()

        connection = sqlite3.connect('./DB/digitization.db')
        cursor = connection.cursor()
        connection.commit()

        query = ("SELECT test_time, test_mode, test_electricity, resistor_AO, resistor_BO, resistor_CO, maximum_unbalance_rate FROM dcr_data WHERE has_report = 0 AND has_delete = "
                 "0 AND station = ? AND position = ?")
        cursor.execute(query, (station, position))
        results = cursor.fetchall()

        self.m_dcr_widget.tableWidget.setRowCount(len(results))

        header = self.m_dcr_widget.tableWidget.horizontalHeader()
        header.resizeSection(0, 350)
        header.resizeSection(1, 180)
        header.resizeSection(2, 200)
        header.resizeSection(3, 180)
        header.resizeSection(4, 180)
        header.resizeSection(5, 180)
        header.resizeSection(6, 280)
        header.resizeSection(7, 400)
        for row_idx, row_data in enumerate(results):
            for col_idx, col_data in enumerate(row_data):
                self.m_dcr_widget.tableWidget.setItem(row_idx, col_idx, QTableWidgetItem(str(col_data)))

            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)

            button_Upload = QPushButton("上传")
            button_Remove = QPushButton("移出")
            button_Edit = QPushButton("编辑")
            button_Delete = QPushButton("删除")

            button_layout.addWidget(button_Upload)
            button_layout.addWidget(button_Remove)
            button_layout.addWidget(button_Edit)
            button_layout.addWidget(button_Delete)

            self.m_dcr_widget.tableWidget.setCellWidget(row_idx, 7, button_widget)

            button_Upload.clicked.connect(lambda _, r=row_idx: self.TableUpload(r))
            button_Remove.clicked.connect(lambda _, r=row_idx: self.TableRemove(r, '直流电阻测试仪'))
            button_Edit.clicked.connect(lambda _, r=row_idx: self.TableEdit(r))
            button_Delete.clicked.connect(lambda _, r=row_idx: self.TableDelete(r, '直流电阻测试仪'))

    def DCR_ChartData(self):
        try:

            # 启用鼠标滚轮缩放功能
            # self.m_dcr_widget.canvas.mpl_connect('scroll_event', self.zoom)
            # # 启用鼠标拖动平移功能
            # self.m_dcr_widget.canvas.mpl_connect('button_press_event', self.on_press)
            # self.m_dcr_widget.canvas.mpl_connect('button_release_event', self.on_release)
            # self.m_dcr_widget.canvas.mpl_connect('motion_notify_event', self.on_motion)

            matplotlib.rc("font", family='YouYuan')

            self.m_dcr_widget.tableWidget.hide()
            self.m_dcr_widget.canvas.show()

            conn = sqlite3.connect('./DB/digitization.db')
            query = """
                    SELECT test_time, test_electricity, resistor_AO, resistor_BO, resistor_CO, maximum_unbalance_rate 
                    FROM dcr_data 
                    WHERE has_report = 0 AND has_delete = 0
                    """

            df = pd.read_sql_query(query, conn)
            conn.close()

            df['test_time'] = pd.to_datetime(df['test_time'], errors='coerce')

            df = df.dropna(subset=['test_time', 'test_electricity', 'resistor_AO', 'resistor_BO', 'resistor_CO'])

            df['test_electricity'] = df['test_electricity'].astype(str)
            df['resistor_AO'] = df['resistor_AO'].astype(float)
            df['resistor_BO'] = df['resistor_BO'].astype(float)
            df['resistor_CO'] = df['resistor_CO'].astype(float)

            ax = self.m_dcr_widget.canvas.figure.add_subplot(111)
            ax.clear()

            ax.plot(df['test_time'], df['test_electricity'], label='电流', color='blue')
            ax.set_xlabel('测试时间')
            ax.set_ylabel('测试电流（mA）', color='blue')
            ax.tick_params(axis='y', labelcolor='blue')

            ax2 = ax.twinx()
            ax2.plot(df['test_time'], df['resistor_AO'], label='电阻AN', color='red', linestyle='--')
            ax2.plot(df['test_time'], df['resistor_BO'], label='电阻BN', color='green', linestyle='-.')
            ax2.plot(df['test_time'], df['resistor_CO'], label='电阻CN', color='purple', linestyle=':')
            ax2.set_ylabel('电阻（mΩ）', color='black')
            ax2.tick_params(axis='y', labelcolor='black')

            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
            self.m_dcr_widget.canvas.figure.autofmt_xdate()

            self.x_min = df['test_time'].min()
            self.x_max = df['test_time'].max()
            self.y_min = min(df['resistor_AO'].min(), df['resistor_BO'].min(), df['resistor_CO'].min())
            self.y_max = max(df['resistor_AO'].max(), df['resistor_BO'].max(), df['resistor_CO'].max())

            self.initial_xlim = [mdates.date2num(self.x_min), mdates.date2num(self.x_max)]
            self.initial_ylim = [self.y_min, self.y_max]

            ax.legend(loc='upper left')
            ax2.legend(loc='upper right')

            self.m_dcr_widget.canvas.draw()
        except Exception as e:
            print('绘制折线图失败：', e)
            logger.critical(f'绘制折线图失败:{e}')

    # 回路电阻测试仪的表格和折线图
    def LR_TableData(self):
        # 获取当前tree widget的节点
        station, position = self.Get_Tree_Node()

        # 隐藏绘图画布并显示表格部件
        self.m_lr_widget.canvas.hide()
        self.m_lr_widget.tableWidget.show()

        connection = sqlite3.connect('./DB/digitization.db')
        cursor = connection.cursor()
        connection.commit()

        query = "SELECT test_time, resistance, current, voltage FROM loop_resistance_data WHERE has_report = 0 AND has_delete = 0 AND station = ? AND position = ?"
        cursor.execute(query, (station, position))
        results = cursor.fetchall()

        self.m_lr_widget.tableWidget.setRowCount(len(results))

        header = self.m_lr_widget.tableWidget.horizontalHeader()
        header.resizeSection(0, 350)  # 测试时间
        header.resizeSection(1, 240)  # 电流
        header.resizeSection(2, 240)  # 电阻
        header.resizeSection(3, 240)  # 电压
        header.resizeSection(4, 400)  # 操作
        for row_idx, row_data in enumerate(results):
            for col_idx, col_data in enumerate(row_data):
                self.m_lr_widget.tableWidget.setItem(row_idx, col_idx, QTableWidgetItem(str(col_data)))

            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)

            button_Upload = QPushButton("上传")
            button_Remove = QPushButton("移出")
            button_Edit = QPushButton("编辑")
            button_Delete = QPushButton("删除")

            button_layout.addWidget(button_Upload)
            button_layout.addWidget(button_Remove)
            button_layout.addWidget(button_Edit)
            button_layout.addWidget(button_Delete)

            self.m_lr_widget.tableWidget.setCellWidget(row_idx, 4, button_widget)

            button_Upload.clicked.connect(lambda _, r=row_idx: self.TableUpload(r))
            button_Remove.clicked.connect(lambda _, r=row_idx: self.TableRemove(r, '回路电阻测试仪'))
            button_Edit.clicked.connect(lambda _, r=row_idx: self.TableEdit(r))
            button_Delete.clicked.connect(lambda _, r=row_idx: self.TableDelete(r, '回路电阻测试仪'))

    def LR_ChartData(self):
        try:

            # 启用鼠标滚轮缩放功能
            # self.m_lr_widget.canvas.mpl_connect('scroll_event', self.zoom)
            # # 启用鼠标拖动平移功能
            # self.m_lr_widget.canvas.mpl_connect('button_press_event', self.on_press)
            # self.m_lr_widget.canvas.mpl_connect('button_release_event', self.on_release)
            # self.m_lr_widget.canvas.mpl_connect('motion_notify_event', self.on_motion)

            matplotlib.rc("font", family='YouYuan')

            self.m_lr_widget.tableWidget.hide()
            self.m_lr_widget.canvas.show()

            conn = sqlite3.connect('./DB/digitization.db')
            query = """
                    SELECT test_time, resistance, current, voltage
                    FROM loop_resistance_data 
                    WHERE has_report = 0 AND has_delete = 0
                    """

            df = pd.read_sql_query(query, conn)
            conn.close()

            df['test_time'] = pd.to_datetime(df['test_time'], errors='coerce')

            df = df.dropna(subset=['test_time', 'resistance', 'current', 'voltage'])

            df['resistance'] = df['resistance'].astype(float)
            df['current'] = df['current'].astype(float)
            df['voltage'] = df['voltage'].astype(float)

            ax = self.m_lr_widget.canvas.figure.add_subplot(111)
            ax.clear()

            ax.plot(df['test_time'], df['resistance'], label='电阻', color='blue')
            ax.set_xlabel('测试时间')
            ax.set_ylabel('电阻（mΩ）', color='blue')
            ax.tick_params(axis='y', labelcolor='blue')

            ax2 = ax.twinx()
            ax2.plot(df['test_time'], df['current'], label='电流(mA)', color='red', linestyle='--')
            ax2.plot(df['test_time'], df['voltage'], label='电压(mV)', color='green', linestyle='-.')
            ax2.set_ylabel('电阻（mΩ）', color='black')
            ax2.tick_params(axis='y', labelcolor='black')

            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
            self.m_lr_widget.canvas.figure.autofmt_xdate()

            self.x_min = df['test_time'].min()
            self.x_max = df['test_time'].max()
            self.y_min = min(df['resistance'].min(), df['current'].min(), df['voltage'].min())
            self.y_max = max(df['resistance'].max(), df['current'].max(), df['voltage'].max())

            self.initial_xlim = [mdates.date2num(self.x_min), mdates.date2num(self.x_max)]
            self.initial_ylim = [self.y_min, self.y_max]

            ax.legend(loc='upper left')
            ax2.legend(loc='upper right')

            self.m_lr_widget.canvas.draw()
        except Exception as e:
            print('绘制折线图失败：', e)
            logger.critical(f'绘制折线图失败:{e}')

    # 接地导通仪的“数据管理”界面表格
    def EC_TableData(self):
        # 获取当前tree widget的节点
        station, position = self.Get_Tree_Node()

        # 隐藏绘图画布并显示表格部件
        self.m_ec_widget.canvas.hide()
        self.m_ec_widget.tableWidget.show()

        connection = sqlite3.connect('./DB/digitization.db')
        cursor = connection.cursor()
        connection.commit()

        query = "SELECT test_time, resistance, current FROM earth_continuity WHERE has_report = 0 AND has_delete = 0 AND station = ? AND position = ?"
        cursor.execute(query, (station, position))
        results = cursor.fetchall()
        # print(results)

        self.m_ec_widget.tableWidget.setRowCount(len(results))

        header = self.m_ec_widget.tableWidget.horizontalHeader()
        header.resizeSection(0, 350)  # 测试时间
        header.resizeSection(1, 240)  # 电流
        header.resizeSection(2, 240)  # 电阻
        header.resizeSection(3, 400)  # 操作
        for row_idx, row_data in enumerate(results):
            for col_idx, col_data in enumerate(row_data):
                self.m_ec_widget.tableWidget.setItem(row_idx, col_idx, QTableWidgetItem(str(col_data)))

            button_widget = QWidget()
            button_layout = QHBoxLayout(button_widget)
            button_layout.setContentsMargins(0, 0, 0, 0)

            button_Upload = QPushButton("上传")
            button_Remove = QPushButton("移出")
            button_Edit = QPushButton("编辑")
            button_Delete = QPushButton("删除")

            button_layout.addWidget(button_Upload)
            button_layout.addWidget(button_Remove)
            button_layout.addWidget(button_Edit)
            button_layout.addWidget(button_Delete)

            self.m_ec_widget.tableWidget.setCellWidget(row_idx, 3, button_widget)

            button_Upload.clicked.connect(lambda _, r=row_idx: self.TableUpload(r))
            button_Remove.clicked.connect(lambda _, r=row_idx: self.TableRemove(r, '接地导通仪'))
            button_Edit.clicked.connect(lambda _, r=row_idx: self.TableEdit(r))
            button_Delete.clicked.connect(lambda _, r=row_idx: self.TableDelete(r, '接地导通仪'))

    def EC_ChartData(self):
        try:
            matplotlib.rc("font", family='YouYuan')

            self.m_ec_widget.tableWidget.hide()
            self.m_ec_widget.canvas.show()

            conn = sqlite3.connect('./DB/digitization.db')
            query = """
                            SELECT test_time, resistance, current
                            FROM earth_continuity 
                            WHERE has_report = 0 AND has_delete = 0
                            """

            df = pd.read_sql_query(query, conn)
            conn.close()

            df['test_time'] = pd.to_datetime(df['test_time'], errors='coerce')

            df = df.dropna(subset=['test_time', 'resistance', 'current'])

            df['resistance'] = df['resistance'].astype(float)
            df['current'] = df['current'].astype(float)

            ax = self.m_ec_widget.canvas.figure.add_subplot(111)
            ax.clear()

            ax.plot(df['test_time'], df['resistance'], label='电阻', color='blue')
            ax.set_xlabel('测试时间')
            ax.set_ylabel('电阻（mΩ）', color='blue')
            ax.tick_params(axis='y', labelcolor='blue')

            ax2 = ax.twinx()
            ax2.plot(df['test_time'], df['current'], label='电流(mA)', color='red', linestyle='--')
            ax2.set_ylabel('电流（mA）', color='black')
            ax2.tick_params(axis='y', labelcolor='black')

            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
            self.m_lr_widget.canvas.figure.autofmt_xdate()

            self.x_min = df['test_time'].min()
            self.x_max = df['test_time'].max()
            self.y_min = min(df['resistance'].min(), df['current'].min())
            self.y_max = max(df['resistance'].max(), df['current'].max())

            self.initial_xlim = [mdates.date2num(self.x_min), mdates.date2num(self.x_max)]
            self.initial_ylim = [self.y_min, self.y_max]

            ax.legend(loc='upper left')
            ax2.legend(loc='upper right')

            self.m_ec_widget.canvas.draw()
        except Exception as e:
            print('绘制折线图失败：', e)
            logger.critical(f'绘制折线图失败:{e}')

    # 折线图缩放
    def zoom(self, event: MouseEvent):
        base_scale = 1.2
        ax = self.m_lr_widget.canvas.figure.gca()
        if event.step > 0:
            scale_factor = 1 / base_scale
        elif event.step < 0:
            scale_factor = base_scale
        else:
            scale_factor = 1

        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

        xdata = event.xdata
        ydata = event.ydata

        new_xlim = [xdata - (xdata - xlim[0]) * scale_factor, xdata + (xlim[1] - xdata) * scale_factor]
        new_ylim = [ydata - (ydata - ylim[0]) * scale_factor, ydata + (ylim[1] - ydata) * scale_factor]

        new_xlim[0] = max(new_xlim[0], self.initial_xlim[0])
        new_xlim[1] = min(new_xlim[1], self.initial_xlim[1])
        new_ylim[0] = max(new_ylim[0], self.initial_ylim[0])
        new_ylim[1] = min(new_ylim[1], self.initial_ylim[1])

        ax.set_xlim(new_xlim)
        ax.set_ylim(new_ylim)

        self.m_lr_widget.canvas.draw()

    def on_press(self, event: MouseEvent):
        # 存储鼠标按下的位置和轴限制用于平移操作
        if event.button == MouseButton.LEFT:
            self.press = event.x, event.y, self.m_lr_widget.canvas.figure.gca().get_xlim(), self.m_lr_widget.canvas.figure.gca().get_ylim()

    def on_release(self, event: MouseEvent):
        # 在释放鼠标按钮后重置按下的数据
        self.press = None
        self.m_dcr_widget.canvas.draw()

    def on_motion(self, event: MouseEvent):
        try:
            # 当按住鼠标左键移动时执行平移操作
            if self.press is None or event.button != MouseButton.LEFT:
                return
            xpress, ypress, xlim, ylim = self.press
            dx = event.x - xpress
            dy = event.y - ypress

            ax = self.m_dcr_widget.canvas.figure.gca()
            scale_x = (xlim[1] - xlim[0]) / self.m_dcr_widget.canvas.figure.get_size_inches()[0] / self.m_dcr_widget.canvas.figure.dpi
            scale_y = (ylim[1] - ylim[0]) / self.m_dcr_widget.canvas.figure.get_size_inches()[1] / self.m_dcr_widget.canvas.figure.dpi

            # 根据鼠标移动更新轴限制
            ax.set_xlim([xlim[0] - dx * scale_x, xlim[1] - dx * scale_x])
            ax.set_ylim([ylim[0] - dy * scale_y, ylim[1] - dy * scale_y])

            # 确保平移不会超出初始的轴限制
            ax.set_xlim([max(ax.get_xlim()[0], self.initial_xlim[0]), min(ax.get_xlim()[1], self.initial_xlim[1])])
            ax.set_ylim([max(ax.get_ylim()[0], self.initial_ylim[0]), min(ax.get_ylim()[1], self.initial_ylim[1])])

            # 重新绘制画布
            self.m_dcr_widget.canvas.draw()
        except Exception as e:
            print('折线图移动错误：', e)

    # 表格-上传
    def TableUpload(self, row):
        instrument = ''
        try:
            # 获取当前行的信息
            data = self.get_row_data(row)
            instrument_data = None
            # 获取被点击的按钮
            button = self.sender()

            # 获取按钮的所有父类的 objectName
            found = False
            parent_names = []
            parent = button.parent()
            while parent:
                # 判断——直流电阻测试仪
                if parent.objectName() == "m_dcr_widget":
                    instrument = "直流电阻测试仪"
                    found = True
                elif parent.objectName() == "m_lr_widget":
                    instrument = '回路电阻测试仪'
                    found = True
                elif parent.objectName() == 'm_ec_widget':
                    instrument = '接地导通仪'
                    found = True
                parent = parent.parent()

            # print("Button parent object names:", " -> ".join(parent_names))
            if instrument == "直流电阻测试仪":
                instrument_data = {
                    # TODO: 直流电阻测试仪有好几种厂家的不同产品，是否需要做出区分
                    "仪器厂家": "金源仪器",
                    "仪器型号": "40S直流电阻测试仪",
                    "仪器出厂编号": "未指定仪器编码",
                    "规范版本号": "1.0.0.0",
                    "分接编号": "未指定",
                    "电流": float(data[2]) * 1000,
                    "电流单位": "mA",
                    "AN/AB电阻": data[3],
                    "BN/BC电阻": data[4],
                    "CN/CA电阻": data[5],
                    "电阻单位": "mΩ"
                    # 41008
                }
            elif instrument == "回路电阻测试仪":
                instrument_data = {
                    "仪器厂家": "武汉智能通",
                    "仪器型号": "ZNT-5010高精度回路电阻测试仪",
                    "仪器出厂编号": "未指定仪器编码",
                    "规范版本号": "1.0.0.0",
                    "分接编号": "未指定",
                    "实测电流": float(data[2]) * 1000,
                    "电流单位": "mA",
                    "实测电阻": data[3],
                    "电阻单位": "mΩ",
                    "实测电压": data[4],
                    "电压单位": 'mV'
                    # 41009
                }
            elif instrument == "接地导通仪":
                instrument_data = {
                    "仪器厂家": "武汉国电中星",
                    "仪器型号": "ZXDT-10C",
                    "仪器出厂编号": "",
                    "规范版本号": "1.0.0.0",
                    "电流": float(data[0]) * 1000,
                    "电流单位": "A",
                    "电阻": float(data[1]) * 1000,
                    "电阻单位": "Ω"
                    # 41016
                }
            # print(type(instrument_data))
            # 将当前行的信息传入上传界面
            self.ShowUpload()
            self.UploadWindow.Signal_Get_Data.emit(instrument_data)
        except Exception as e:
            print('呼出UploadWindow错误：', e)
            logger.critical(f'呼出UploadWindow错误：{e}')

    # 表格- 移出
    def TableRemove(self, row, instrument):
        data = self.get_row_data(row)
        print(data)
        # 数据库删除
        try:
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()
            if instrument == "直流电阻测试仪":
                cursor.execute("DELETE FROM dcr_data WHERE test_time = ? AND test_mode = ? AND test_electricity = ? AND resistor_AO = ? AND resistor_BO = ? AND resistor_CO = ? AND "
                               "maximum_unbalance_rate = ? AND has_delete = 0 AND has_report = 0",
                               (data[0], data[1], data[2], float(data[3]), float(data[4]), float(data[5]), float(data[6])))
            elif instrument == '回路电阻测试仪':
                cursor.execute("DELETE FROM loop_resistance_data WHERE test_time = ? AND resistance = ? AND current = ? AND voltage = ? AND has_delete = 0 AND has_report = 0",
                               (data[0], data[1], data[2], float(data[3])))
            elif instrument == '接地导通仪':
                cursor.execute("DELETE FROM earth_continuity WHERE test_time = ? AND resistance = ? AND current = ? AND has_delete = 0 AND has_report = 0",
                               (data[0], float(data[1]), float(data[2])))
            connection.commit()
            connection.close()

        except sqlite3.Error as e:
            print("移出错误:", e)
            logger.critical(f'移出错误:{e}')
        finally:
            station, position = self.Get_Tree_Node()
            self.ShowInstrumrnt(station, position)

    def TableEdit(self, row):
        data = self.get_row_data(row)
        print(f"编辑按钮点击 - 行数据: {data}")

    # 表格-删除
    def TableDelete(self, row, instrumrnt):
        # 数据库中置has_delete为1
        data = self.get_row_data(row)
        row_data = self.get_row_data(row)
        try:
            connection = sqlite3.connect('./DB/digitization.db')
            cursor = connection.cursor()
            if instrumrnt == '直流电阻测试仪':
                cursor.execute(("UPDATE dcr_data SET has_delete = 1 WHERE test_time = ? AND test_mode = ? AND test_electricity = ? AND resistor_AO = ? AND resistor_BO = ? AND "
                                "resistor_CO = ? AND maximum_unbalance_rate = ? AND has_delete = 0 AND has_report = 0"), tuple(row_data))
            elif instrumrnt == "回路电阻测试仪":
                cursor.execute(("UPDATE loop_resistance_data SET has_delete = 1 WHERE test_time = ? AND resistance = ? AND current = ? AND voltage = ? AND has_delete = 0 AND "
                                "has_report = 0"), tuple(row_data))
            elif instrumrnt == "接地导通仪":
                cursor.execute("UPDATE earth_continuity SET has_delete = 1 WHERE test_time = ? AND resistance = ? AND current = ? AND has_delete = 0 AND has_report = 0", tuple(row_data))
            connection.commit()
            connection.close()

        except sqlite3.Error as e:
            print("删除错误:", e)
            logger.critical(f'删除错误:{e}')
        finally:
            self.DCR_TableData()

    def get_row_data(self, row):
        row_data = []

        # 获取按钮的所有父类的 objectName
        found = False
        button = self.sender()
        parent = button.parent()
        widget = None
        while parent:
            if parent.objectName() == "m_dcr_widget":
                widget = self.m_dcr_widget
                found = True
            elif parent.objectName() == "m_lr_widget":
                widget = self.m_lr_widget
                found = True
            elif parent.objectName() == 'm_ec_widget':
                widget = self.m_ec_widget
                found = True
            parent = parent.parent()

        for col in range(widget.tableWidget.columnCount() - 1):
            item = widget.tableWidget.item(row, col)
            if item:
                row_data.append(item.text())
            else:
                row_data.append('')
            item.setTextAlignment(Qt.AlignCenter)

        return row_data

    # 获取当前树的节点及其所有父节点
    def Get_Tree_Node(self):
        current_item = self.treeWidget.currentItem()
        position = current_item.text(1)
        station = current_item.parent().text(0)
        # print('station:', station, 'position:', position)
        return station, position

    # 清空布局中的所有控件
    def clearLayout(self, layout):
        while layout.count():
            child = layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

    # 主窗口关闭
    def closeEvent(self, event):
        for widget in QApplication.topLevelWidgets():
            if isinstance(widget, QWidget) and widget != self:
                EdgeIOT.CloseConnection()
                widget.close()
        # 关闭线程
        # root.quit()

    # 监测信息设置窗口
    def ShowSetup(self):
        self.SetupWindow.show()
        # 站点窗口

    # 数据上传窗口
    def ShowUpload(self):
        self.UploadWindow.show()

    # 导出报告窗口呼出
    # TODO: 分类型
    # FIXME: 会报错:呼出报告窗口失败:'QWidget' object has no attribute 'tableWidget'
    def ShowExport(self, widget):
        try:
            all_data = []
            for row in range(self.widget.tableWidget.rowCount()):
                row_data = self.get_row_data(row)
                all_data.append(row_data)
            # for data in all_data:
            #     print(data)
            self.ExportWindow.show()
            self.ExportWindow.Signal_Position_Data.emit(all_data, self.widget.label_Instrument_2.text())
        except Exception as e:
            print('呼出报告窗口失败:', e)
            logger.critical(f'呼出报告窗口失败:{e}')

    # 仪器信息修改窗口呼出
    def ShowModify(self):
        try:
            self.InstrumentWindow = InstrumentWindow(self)
            self.InstrumentWindow.show()
        except Exception as e:
            print('Show Modify Window ERROR:', e)

    # 监测站点窗口呼出
    def ShowDetect(self):
        self.DetectWindow.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())
